/**
 * 
 */
package org.gigi.security.service.base;

import java.util.ArrayList;
import java.util.List;

import org.gigi.security.domain.Authority;
import org.gigi.security.domain.Menu;
import org.gigi.security.repository.AuthorityRepository;
import org.gigi.security.repository.MenuRepository;
import org.gigi.security.service.MenuService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 默认的菜单服务层实现
 *
 * @author Eugene Wang 2011-9-13
 * @see
 */
@Service
@Transactional(readOnly = true)
public class DefaultMenuService implements MenuService {
	@Autowired
	private MenuRepository menuRepository;
	@Autowired
	private AuthorityRepository authorityRepository;

	/* (non-Javadoc)
	 * @see org.gigi.security.service.MenuService#findAll()
	 */
	@Override
	public List<Menu> findChildren(String code) {
		List<Menu> result = menuRepository.findChildren(code);
		return result;
	}

	/* (non-Javadoc)
	 * @see org.gigi.security.service.MenuService#create(org.gigi.security.domain.Menu)
	 */
	@Override
	@Transactional
	public void create(Menu menu) {
		menuRepository.create(menu);
	}

	/* (non-Javadoc)
	 * @see org.gigi.security.service.MenuService#delete(java.lang.String)
	 */
	@Override
	@Transactional
	public void delete(String code) {
		Menu menu = menuRepository.findByCode(code);
		menuRepository.delete(menu);
	}

	/* (non-Javadoc)
	 * @see org.gigi.security.service.MenuService#update(org.gigi.security.domain.Menu)
	 */
	@Override
	@Transactional
	public void update(Menu menu) {
		Menu dbMenu = menuRepository.findByCode(menu.getCode());
		BeanUtils.copyProperties(menu, dbMenu, new String[] {"parent", "authority"});
		if (menu.getAuthority() != null) {
			Authority authority = authorityRepository.load(menu.getAuthority().getCode());
			dbMenu.setAuthority(authority);
		} else {
			dbMenu.setAuthority(null);
		}
		menuRepository.update(dbMenu);
	}

	/* (non-Javadoc)
	 * @see org.gigi.security.service.MenuService#findByCode(java.lang.String)
	 */
	@Override
	public Menu findByCode(String code) {
		return menuRepository.findByCode(code);
	}

	/* (non-Javadoc)
	 * @see org.gigi.security.service.MenuService#findAll()
	 */
	@Override
	public List<Menu> findAll() {
		List<Menu> result = new ArrayList<Menu>();
		List<Menu> all = menuRepository.findAll();
		for (Menu menu : all) {
			if (menu.getParent() == null) {
				result.add(menu);
			} else {
				menu.getParent().addChild(menu);
			}
		}
		return result;
	}
}
